/**
 *
 * 
<surf:container id="comcenter-surface-friends_2832660534560290673">
    <li id="comcenter-2832660534560290673" class="comcenter-friend-item comcenter-friend comcenter-friend-playing comcenter-friend-online " rel="2832660534560290673">
        <div class="comcenter-friend-draggable"></div>
        <div class="comcenter-avatar">
            <div class="base-avatar-container base-avatar-size-small" rel="2832660534560290673">
                <div class="base-avatar-status-overlay base-avatar-status-overlay-playing">
                    <img width="22" height="22" src="http://www.gravatar.com/avatar/75a2a60de41ea82b44eb52a91895edb2?s=22&d=http%3A%2F%2Fbattlelog-cdn.battlefield.com%2Fpublic%2Fbase%2Fshared%2Fdefault-avatar-22.png%3Fv%3D7910">
                </div>
            </div>
        </div>
        <div class="comcenter-username">
            <a class="comcenter-username-link" data-profile="/bf3/user/Cheffwil/">Cheffwil</a>
            <div class="comcenter-username-serverinfo">
                <div class="base-left">
                    <span class="comcenter-full-height common-gameicon-hori bright common-game-2-1-exp comcenter-game-icon"></span>
                    <span class="comcenter-small-height common-gameicon-hori common-game-2-1-exp comcenter-game-icon"></span>
                </div>
                <div class="base-left">
                    <span class="common-playing-link">
                        <a class="common-playing-link base-no-ajax comcenter-playing-link" href="/bf3/servers/show/126d758d-295a-4ba3-92a1-89f12c519637/I-m-a-Schnecke-FaTz-CloseQ-All-Maps-TDM-u-Domination/" title="I'm a Schnecke - FaTz / CloseQ / All Maps / TDM u. Domination"> I'm a Schnecke -... </a>
                    </span>
                </div>
            </div>
        </div>
        <div class="comcenter-interact-container">
            <form class="join-friend " action="/bf3/servers/show/126d758d-295a-4ba3-92a1-89f12c519637/I-m-a-Schnecke-FaTz-CloseQ-All-Maps-TDM-u-Domination/" method="POST">
                <input type="hidden" value="unset" name="post-check-sum">
                <input type="hidden" value="2" name="game">
                <input type="hidden" value="187617568" name="friendPersonaId">
                <input type="hidden" value="126d758d-295a-4ba3-92a1-89f12c519637" name="guid">
                <div class="bubble-title-left join-friend-submit-link comcenter-interact-playing" title="Join Game"></div>
            </form>
            <button class="bubble-title-left comcenter-interact-chat" title="Chat"></button>
        </div>
    </li>
</surf:container>
 *
 */

var PlatoonFriends = {
    updateInterval : 60*5,
    init : function () {
        
        var friendListSurface = $S("comcenter-surface-friends");
        friendListSurface.oldUpdate = friendListSurface.update;
        friendListSurface.update = function(itemState, opts) { var ret = this.oldUpdate(itemState, opts); PlatoonFriends.update(); return ret;}
        friendListSurface.oldRefresh = friendListSurface.refresh;
        friendListSurface.refresh = function() { var ret = this.oldRefresh(); PlatoonFriends.update(); return ret;}
        
//        PlatoonFriends.update();
        setInterval(function(){ PlatoonFriends.update(); }, this.updateInterval * 1000);
    },
    
    update : function() {	
        var platoons = Surface.globalContext.userContext.platoons;
        var platoonsObj = [];
        var playerList = [];
        for (var i = 0; i < platoons.length; i++) {
            var id = platoons[i].id;
            platoonsObj[i] = 
            {
                platoonName : platoons[i].name,
                platoonId : id,
                platoonShow : true
            }

            playerList[id] = []; 

            BBLog.getJSONFromBattlelog(PlatoonFriends.Helpers.makeLocalizedUrl("/platoon/" +  id + "/listmembers/"), function(json){
                playerList[id] = PlatoonFriends.Platoon.parseOnlineMembers(json);
                PlatoonFriends.displayPlayerList(platoonsObj, playerList);
//                alert(playerList[id]);
            });
            
        }

    },
    
    displayPlayerList : function(platoons, playerList) {
        
        for (var i = 0; i < platoons.length; i++) {
            var id = platoons[i].platoonId;
            // check if container used to add our players exists
            var platoonContainer = $('#comcenterPlatoonFriends-'+id);
			
            if(platoonContainer.length > 0) {
                // if yes, clear it
                platoonContainer.empty();
            } else {
                // if no, create it
                $('#comcenter-surface-friends #comcenterOnlineFriends').before(
                    $('<surf:container>').attr('id', 'comcenterPlatoonFriends-'+id)
                    );
                 
//                $('#comcenter-surface-friends .comcenter-add-friend').before(
//                    $('<surf:container>').attr('id', 'comcenterPlatoonFriends-'+id)
//                    );
            }
            
            var playerNum = (playerList[id].length <= 0) ? 0 :  playerList[id].length - 1;
            // create the separator
            PlatoonFriends.displayComcenterSeparator(playerNum, id, platoons[i]);
            
            var comcenterOnlineSep = $("#comcenter-online-separator span");
            comcenterOnlineSep.text(parseInt(comcenterOnlineSep.text()) - playerNum + " friends online");
            
            // display each player
            for (var j = 0; j < playerList[id].length; j++) {
                var player = playerList[id][j];
                PlatoonFriends.displayPlayer(player, id);
            }
			
            // collapse the platoon friend list if it was previously collapsed
            var bar = $("#comcenter-platoonfriends-" + id + "-separator");
            if(bar.data('platoonShow')) {
                bar.addClass("showing-online");
                $(".comcenter-platoonfriend-"+id+"-online").removeClass("comcenter-friend-hidden");
            }
        }
        // ask battlelog to resize the comcenter
        comcenter.resizeComCenter();
    },
    
    displayPlayer : function(player, platoonId) {
        var playerContainer = $('<surf:container>').attr('id', 'comcenter-surface-friends_' + player.userId);
        
        var playerElement = $('#comcenter-surface-friends_' + player.userId);
        
//        .removeClass('comcenter-friend-online')
        
        playerElement.find('#comcenter-' + player.userId).addClass("comcenter-platoonfriend-"+platoonId+"-online");
        
        playerContainer.append(playerElement.clone());
        playerElement.remove();
             
        $('#comcenterPlatoonFriends-'+platoonId).append(playerContainer);
    },
    
    displayComcenterSeparator : function(playerCount, platoonId, platoon) {
        var separator = $('<li>').attr('id', 'comcenter-platoonfriends-' + platoonId + '-separator').addClass("comcenter-separator showing-online");
        
        $('#comcenterPlatoonFriends-' + platoonId).append(
            separator.append(
                $('<div>').addClass('dropdownicon')
                ).append(
                $('<surf:container>').attr('id', 'comcenterPlatoonFriends-' + platoonId).append(
                    $('<span>').text(playerCount.toString() + ' ' + platoon.platoonName)
                    )
                )
            );
                
        separator.bind("click", function (e) {
            var bar = $("#comcenter-platoonfriends-" + platoonId + "-separator");
            if (bar.hasClass("showing-online")) {
                bar.removeClass("showing-online");
                $(".comcenter-platoonfriend-"+platoonId+"-online").addClass("comcenter-friend-hidden");
                bar.data('platoonShow', false);
            } else {
                bar.addClass("showing-online");
                $(".comcenter-platoonfriend-"+platoonId+"-online").removeClass("comcenter-friend-hidden");
                bar.data('platoonShow', true);
            }
            comcenter.resizeComCenter();
        });
    },

    makeCallbackWithParam : function(f, p) {
        var self = this;
        return function(json) {
            f.call(self, json, p);
        }
    }
}

PlatoonFriends.Helpers = {
    makeLocalizedUrl : function(path){
        var url = "";
        if(BBLog.battlelogLanguage != null && BBLog.battlelogLanguage != 'en')
            url = '/bf3/' + BBLog.battlelogLanguage + path;
        else
            url = '/bf3' + path;
        return url;
    }
};

PlatoonFriends.Platoon = {
    parseOnlineMembers : function(json) {
        var members = json.context.listMembers;
        var id = json.context.platoon.id;
        var playerList = [];

        for(var i in members) {
            var member = members[i];
            var user = member.user;

            // if player is member of the platoon (not only invited) and in a PC game
            //if(member.membershipLevel >= 4 && user.presence.isPlaying && user.presence.platform == 1 )
            if(member.membershipLevel >= 4 && user.presence.isOnline && json.context.me.userId != user.userId) {
                var player =
                {
                    name : user.username,
                    userId : user.userId,
                    personaId : member.personaId,
                    userAvatar : user.gravatarMd5,
                    serverGuid : user.presence.serverGuid,
                    serverName : user.presence.serverName
                }

                playerList.push(player);
            }
        }
//        return playerList;
        return (playerList.length > 0) ? playerList : [];
    }
}

var handler = function () {
    PlatoonFriends.init();
}
$(document).ready(function() { 
//    BBLog.bindDomChange(handler);
//    handler();
    PlatoonFriends.init();
    PlatoonFriends.update();
});
